package eco2automotive.gui.components;
import javax.swing.*;
import java.awt.*;
import gnu.io.*;
import java.util.*;
import java.awt.event.*;

/** 
  * JPanel utility for the selection of ports availables
  * @version 1.0
  * @autor Fco. Javier Sánchez Esparza
 */
public class Panel_PORT_FINDER extends JPanel implements ItemListener {

protected HashMap map = new HashMap();
protected String selectedPortName;
protected CommPortIdentifier selectedPortIdentifier;
protected JComboBox serialPortsChoice;
protected JComboBox parallelPortsChoice;
protected JComboBox other;
protected SerialPort ttya;

public void itemStateChanged(ItemEvent e) {
    selectedPortName = (String)((JComboBox)e.getSource()).getSelectedItem();
    selectedPortIdentifier = (CommPortIdentifier)map.get(selectedPortName);
    System.out.println("Your Select: "+selectedPortName);
}
/**
 * Returns the port name selected
 * @return
 */
public String getSelectedName() {
return selectedPortName;
}
/**
 * Returns the port id.
 * @return
 */
public CommPortIdentifier getSelectedIdentifier() {
return selectedPortIdentifier;
}
/**
 * Create a new
 */
public Panel_PORT_FINDER(){  
    
        setBorder(new javax.swing.border.TitledBorder("Available Ports..."));
        serialPortsChoice = new JComboBox();            
        parallelPortsChoice = new JComboBox();
        other=new JComboBox();
        serialPortsChoice.setEnabled(false);
        parallelPortsChoice.setEnabled(false);
        other.setEnabled(false);
        this.setLayout (new GridLayout(1,3));
        this.add(serialPortsChoice);
        this.add(parallelPortsChoice);
        this.add(other);
        start();
        actions();
}
/**
 * Add the listeners
 */
protected void actions(){
    serialPortsChoice.addItemListener(this);
    parallelPortsChoice.addItemListener(this);
    other.addItemListener(this);
}
/**
 * start
 */
protected void start() {
Enumeration pList = CommPortIdentifier.getPortIdentifiers();
serialPortsChoice.addItem("<none>");
parallelPortsChoice.addItem("<none>");

while (pList.hasMoreElements()) {
CommPortIdentifier cpi = (CommPortIdentifier)pList.nextElement();
map.put(cpi.getName(), cpi);
    if (cpi.getPortType() == CommPortIdentifier.PORT_SERIAL) {
    serialPortsChoice.setEnabled(true);
    serialPortsChoice.addItem(cpi.getName());
        } else if (cpi.getPortType() == CommPortIdentifier.PORT_PARALLEL) {
            parallelPortsChoice.setEnabled(true);
            parallelPortsChoice.addItem(cpi.getName());
    } else {
            other.setEnabled(true);
            other.addItem(cpi.getName());
    }
}

serialPortsChoice.setSelectedIndex(-1);
parallelPortsChoice.setSelectedIndex(-1);
}


}
